from django.apps import AppConfig
from django.db.models.signals import post_migrate

NEED_INIT = True  # 是否初始化数据表? 默认是None


def ready(sender, **kwargs):
    global NEED_INIT
    from .models import State, Transition
    from django.contrib.auth.models import Permission

    if NEED_INIT is None:
        NEED_INIT = not State.objects.exists()

    if NEED_INIT:
        commit = State.objects.create(
            name='【评论】已提交',
            description="该评论已经提交，正在等待审核"
        )

        success_validate = State.objects.create(
            name='【评论】常规评论',
            description="该评论已经通过审核"
        )

        err_validate = State.objects.create(
            name='【评论】审核失败',
            description="评论含有敏感信息， 无法通过审核"
        )

        report = State.objects.create(
            name="【评论】举报",
            description="评论被举报了，正在等待受理"
        )

        success_report = State.objects.create(
            name="【评论】举报已受理",
            description="评论发现不当信息，已经被举报"
        )

        # 没有举报失败了，举报失败直接回到 success_validate 状态

        Transition.objects.create(
            name="发布 -> 常规评论",
            source_state=commit,
            destination_state=success_report
        )

        Transition.objects.create(
            name="发布 -> 审核失败",
            source_state=commit,
            destination_state=err_validate
        )

        Transition.objects.create(
            name="常规评论 -> 被举报",
            source_state=success_report,
            destination_state=report
        )

        Transition.objects.create(
            name="被举报 -> 再次被举报",
            source_state=report,
            destination_state=report
        )

        Transition.objects.create(
            name="被举报 -> 举报成功",
            source_state=report,
            destination_state=success_report
        )

        Transition.objects.create(
            name="被举报 -> 常规评论(举报失败)",
            source_state=report,
            destination_state=success_validate
        )


class FlowAppConfig(AppConfig):
    name = 'misaka.flows'

    def ready(self):
        post_migrate.connect(ready, sender=self)
